namespace Voodoo.Sauce.Internal.Ads.MopubMediation
{
	public class MopubInterstitial : InterstitialAd
	{
		private bool _shown;

		public MopubInterstitial(string adUnit, bool autofetch)
			: base("Mopub", adUnit, autofetch)
		{
			MoPubWrapper.LoadInterstitialPluginsForAdUnits(adUnit);
			RegisterEvents();
			AutoFetch();
		}

		protected override void Fetch()
		{
			base.Fetch();
			MoPubAndroid.RequestInterstitialAd(_adUnit, string.Empty, string.Empty);
		}

		public override void Show()
		{
			_shown = false;
			base.Show();
			MoPubAndroid.ShowInterstitialAd(_adUnit);
			VoodooSauceBehaviour.InvokeAfter(ShowTimeout, 5f);
		}

		private void ShowTimeout()
		{
			DebugLog("Interstitial show timeout: " + !_shown);
			if (!_shown)
			{
				DebugLog("Interstitial forced to complete after timeout");
				Complete();
			}
		}

		protected override void RegisterEvents()
		{
			MoPubManager.OnInterstitialShownEvent += OnMoPubShownEvent;
			MoPubManager.OnInterstitialLoadedEvent += OnMoPubLoadedEvent;
			MoPubManager.OnInterstitialClickedEvent += OnMoPubClickedEvent;
			MoPubManager.OnInterstitialDismissedEvent += OnMoPubClosedEvent;
			MoPubManager.OnInterstitialExpiredEvent += OnMoPubExpiredEvent;
			MoPubManager.OnInterstitialFailedEvent += OnMoPubFailedEvent;
		}

		protected override void UnregisterEvents()
		{
			base.UnregisterEvents();
			MoPubManager.OnInterstitialShownEvent -= OnMoPubShownEvent;
			MoPubManager.OnInterstitialLoadedEvent -= OnMoPubLoadedEvent;
			MoPubManager.OnInterstitialClickedEvent -= OnMoPubClickedEvent;
			MoPubManager.OnInterstitialDismissedEvent -= OnMoPubClosedEvent;
			MoPubManager.OnInterstitialExpiredEvent -= OnMoPubExpiredEvent;
			MoPubManager.OnInterstitialFailedEvent -= OnMoPubFailedEvent;
		}

		private void OnMoPubShownEvent(string adUnit)
		{
			if (!(adUnit != _adUnit))
			{
				_shown = true;
				DebugLog("OnMoPubShownEvent");
			}
		}

		private void OnMoPubLoadedEvent(string adUnit)
		{
			if (!(adUnit != _adUnit))
			{
				OnAdLoadedCallback();
			}
		}

		private void OnMoPubClickedEvent(string adUnit)
		{
			if (!(adUnit != _adUnit))
			{
				OnAdClickedCallback();
			}
		}

		private void OnMoPubClosedEvent(string adUnit)
		{
			if (!(adUnit != _adUnit))
			{
				OnAdClosedCallback();
			}
		}

		private void OnMoPubExpiredEvent(string adUnit)
		{
			if (!(adUnit != _adUnit))
			{
				OnAdExpiredCallback();
			}
		}

		private void OnMoPubFailedEvent(string adUnit, string errorMsg)
		{
			if (!(adUnit != _adUnit))
			{
				OnAdFailedCallback();
			}
		}
	}
}
